package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.juhe.sdk.ApiClient;
import com.juhe.sdk.common.Result;
import com.juhe.sdk.reqeust.GetPersonalHouseResponse;
import com.juhe.sdk.reqeust.IdCardVerifyRequst;
import com.juhe.sdk.reqeust.PersonalHouseRequest;
import com.juhe.sdk.reqeust.UploadAuthFile64Request;
import com.juhe.sdk.response.FileInfoResponse;
import com.juhe.sdk.response.LawSuitResponse;
import com.juhe.sdk.response.PersonalHouseResponse;
import com.juhe.sdk.response.PersonalRentApplyResponse;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.domain.dto.FeeResult;
import com.ruoyi.project.system.mapper.*;
import com.ruoyi.project.system.service.ISiyuQueryService;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.utils.DateUtils.*;
import static com.ruoyi.common.utils.file.FileUtils.makeAithFile;
import static com.ruoyi.common.utils.uuid.Seq.getId;

/**
 * 进件记录Service业务层处理
 */
@Slf4j
@Service
public class SiyuQueryServiceImpl implements ISiyuQueryService {

    @Autowired
    private SiyuQueryMapper siyuQueryMapper;

    @Autowired
    private SiyuUserPriceMapper siyuUserPriceMapper;

    @Autowired
    private SiyuProductMapper siyuProductMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SiyuChargeMapper siyuChargeMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private RedisCache redisCache;

    public int setQueryinfo(Integer productId, Integer queryId, String info, Date nowDate) {
        HashMap<String, Object> queryinfo = siyuQueryMapper.selectQueryinfo(productId, queryId);
        if (queryinfo == null || queryinfo.isEmpty()) {
            return siyuQueryMapper.insertQueryinfo(queryId, productId, info, nowDate);
        } else {
            return siyuQueryMapper.updateQueryinfo(Integer.parseInt(queryinfo.get("id").toString()), info, nowDate);
        }
    }

    @Override
    @Transactional
    public AjaxResult queryData(SiyuQuery siyuQuery) {
        SiyuProduct product = siyuProductMapper.selectSiyuProductById(siyuQuery.getProductId());

        JSONObject params = new JSONObject();
        Object result = null;
        if ("syshc".equals(product.getCode())) {
            result = JSON.toJSONString(authInfoQuery(siyuQuery));
        } else if ("blxw".equals(product.getCode())) {
            params.put("name", siyuQuery.getName());
            params.put("cardNo", siyuQuery.getCardNo());
            result = otherInfoQuery("JF002", params);  // MGZ TODO 2025/5/31: 待处理
        } else if ("graj".equals(product.getCode())) {
            params.put("name", siyuQuery.getName());
            params.put("cardNo", siyuQuery.getCardNo());
            result = otherInfoQuery("JF025", params);
        } else if ("hy".equals(product.getCode())) {
            result = JSON.toJSONString(marryQuery(siyuQuery));
        } else if ("qjld".equals(product.getCode())) {
            result = otherInfoQuery("JF027", disNCM(siyuQuery));
        } else if ("dttz".equals(product.getCode())) {
            result = otherInfoQuery("JF011", disNCM(siyuQuery));
        } else if ("sqyx".equals(product.getCode())) {
            result = otherInfoQuery("JF026", disNCM(siyuQuery));
        } else if ("tza".equals(product.getCode())) {
            result = otherInfoQuery("JF028", disNCM(siyuQuery));
        } else if ("jxzs".equals(product.getCode())) {
            result = otherInfoQuery("JF010", disNCM(siyuQuery));
        } else if ("grbdc".equals(product.getCode())) {
            result = addImmovablePropertyQuery(siyuQuery);
        } else if ("qwdbg".equals(product.getCode())) {
            // 全维度报告
            result = allReportQuery(siyuQuery).toJSONString();
        } else if ("rzbd".equals(product.getCode())) {
            // 入职背调
            result = onBoardingSurveyQuery(siyuQuery).toJSONString();
        }

        // 异步扣费
        AsyncManager.me().execute(AsyncFactory.aysFee(siyuQuery, SecurityUtils.getUserId()));
        // 写入查询结果
        Date nowDate = DateUtils.getNowDate();
        setQueryinfo(siyuQuery.getProductId(), siyuQuery.getQueryId(), result.toString(), nowDate);

        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("time", parseDateToStr(YYYY_MM_DD_HH_MM_SS, nowDate));
        ajaxResult.put("info", result);
        return ajaxResult;
    }

    @Override
    public JSONObject reportQuery(JSONObject params) {
        params.put("request_sn", "TZ" + IdUtils.fastSimpleUUID().substring(0, 12).toUpperCase());
        params.put("req_time", System.currentTimeMillis());
        String resInfo = HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json");
        return JSON.parseObject(resInfo);
    }

    private JSONObject disNCM(SiyuQuery siyuQuery) {
        JSONObject params = new JSONObject();
        params.put("mobile", siyuQuery.getTel());
        params.put("name", siyuQuery.getName());
        params.put("cardNo", siyuQuery.getCardNo());
        return params;
    }

    public JSONObject allReportQuery(SiyuQuery siyuQuery) {
        JSONObject ncmData = new JSONObject();
        ncmData.put("name", siyuQuery.getName());
        ncmData.put("cardNo", siyuQuery.getCardNo());
        ncmData.put("mobile", siyuQuery.getTel());
        CompletableFuture<HashMap<String, JSONObject>> zwsc_blxw = CompletableFuture.supplyAsync(() -> {
                    HashMap respMap = new HashMap<String, JSONObject>();

                    JSONObject cData = new JSONObject();
                    cData.put("inter_id", "JF002");
                    cData.put("name", siyuQuery.getName());
                    cData.put("cardNo", siyuQuery.getCardNo());
                    respMap.put("blxw", reportQuery(cData));

                    JSONObject mData = new JSONObject();
                    mData.put("inter_id", "JF030");
                    mData.put("mobile", siyuQuery.getTel());
                    respMap.put("zwsc", reportQuery(mData));

                    return respMap;
                }
        );
        CompletableFuture<HashMap<String, JSONObject>> smrz_sjsys = CompletableFuture.supplyAsync(() -> {
                    HashMap respMap = new HashMap<String, JSONObject>();
                    JSONObject ncData = new JSONObject();
                    ncData.put("inter_id", "JF005");
                    ncData.put("name", siyuQuery.getName());
                    ncData.put("cardNo", siyuQuery.getCardNo());
                    respMap.put("smrz", reportQuery(ncData));
                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF007");
                    reqData.putAll(ncmData);
                    respMap.put("sjsys", reportQuery(reqData));
                    return respMap;
                }
        );
        CompletableFuture<HashMap<String, JSONObject>> qjld_jxzs = CompletableFuture.supplyAsync(() -> {
                    HashMap respMap = new HashMap<String, JSONObject>();

                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF027");
                    reqData.putAll(ncmData);
                    respMap.put("qjld", reportQuery(reqData));

                    JSONObject reqData_ = new JSONObject();
                    reqData_.put("inter_id", "JF010");
                    reqData_.putAll(ncmData);
                    respMap.put("jxzs", reportQuery(reqData_));

                    return respMap;
                }
        );
        CompletableFuture<HashMap<String, JSONObject>> zulin_sf = CompletableFuture.supplyAsync(() -> {
                    HashMap respMap = new HashMap<String, JSONObject>();

                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF026");
                    reqData.putAll(ncmData);
                    respMap.put("zulin", reportQuery(reqData));

                    JSONObject reqData_ = new JSONObject();
                    reqData_.put("inter_id", "JF025");
                    reqData_.putAll(ncmData);
                    respMap.put("sf", reportQuery(reqData_));

                    return respMap;
                }
        );
        CompletableFuture<JSONObject> dq = CompletableFuture.supplyAsync(() -> {
                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF011");
                    reqData.putAll(ncmData);
                    return reportQuery(reqData);
                }
        );
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(zwsc_blxw, smrz_sjsys, qjld_jxzs, zulin_sf, dq);
        allFutures.join();

        JSONObject object = new JSONObject();
        try {
            object.putAll(zwsc_blxw.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.putAll(smrz_sjsys.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.putAll(qjld_jxzs.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.putAll(zulin_sf.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.put("dq", dq.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    @Override
    public JSONObject authInfoQuery(SiyuQuery siyuQuery) {
        JSONObject result = new JSONObject();
        JSONObject params = new JSONObject();
        String baseReqSn = "TZ" + getId();
        params.put("req_time", System.currentTimeMillis());
        // 实名认证
        params.put("request_sn", baseReqSn + "JF005");
        params.put("inter_id", "JF005");
        params.put("name", siyuQuery.getName());
        params.put("cardNo", siyuQuery.getCardNo());
        result.put("smrz", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json")));
        sysConfigMapper.addInterNum();
        // 在网时长
        params.replace("request_sn", baseReqSn + "JF030");
        params.replace("inter_id", "JF030");
        params.put("mobile", siyuQuery.getTel());
        result.put("zwsc", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json")));
        sysConfigMapper.addInterNum();
        // 三要素
        params.replace("request_sn", baseReqSn + "JF007");
        params.replace("inter_id", "JF007");
        result.put("sys", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json")));
        sysConfigMapper.addInterNum();
        return result;
    }

    @Override
    public String otherInfoQuery(String jfCode, JSONObject params) {
        String baseReqSn = "TZ" + getId();
        params.put("req_time", System.currentTimeMillis());
        params.put("request_sn", baseReqSn);
        params.put("inter_id", jfCode);
        sysConfigMapper.addInterNum();
        return HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json");
    }

    @Override
    public JSONObject marryQuery(SiyuQuery siyuQuery) {
        JSONObject result = new JSONObject();
        JSONObject params = new JSONObject();
        String baseReqSn = "TZ" + getId();
        params.put("req_time", System.currentTimeMillis());
        // 实名认证
        params.put("request_sn", baseReqSn + "JF005");
        params.put("inter_id", "JF005");
        params.put("name", siyuQuery.getName());
        params.put("cardNo", siyuQuery.getCardNo());
        result.put("smrz", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json")));
        sysConfigMapper.addInterNum();
        // 婚姻
        params.replace("request_sn", baseReqSn + "JF032");
        params.replace("inter_id", "JF032");
        result.put("hyhy", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json")));
        sysConfigMapper.addInterNum();
        return result;
    }

    @Override
    public JSONObject onBoardingSurveyQuery(SiyuQuery siyuQuery) {
        CompletableFuture<JSONObject> smrz = CompletableFuture.supplyAsync(() -> {
                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF005");
                    reqData.put("name", siyuQuery.getName());
                    reqData.put("cardNo", siyuQuery.getCardNo());
                    return reportQuery(reqData);
                }
        );
        CompletableFuture<JSONObject> sjsys = CompletableFuture.supplyAsync(() -> {
                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF007");
                    reqData.put("name", siyuQuery.getName());
                    reqData.put("cardNo", siyuQuery.getCardNo());
                    reqData.put("mobile", siyuQuery.getTel());
                    return reportQuery(reqData);
                }
        );
//        CompletableFuture<JSONObject> zwsc = CompletableFuture.supplyAsync(() -> {
//                    JSONObject reqData = new JSONObject();
//                    reqData.put("inter_id", "JF030");
//                    reqData.put("mobile", siyuQuery.getTel());
//                    return reportQuery(reqData);
//                }
//        );
        CompletableFuture<JSONObject> blxw = CompletableFuture.supplyAsync(() -> {
                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF002");
                    reqData.put("name", siyuQuery.getName());
                    reqData.put("cardNo", siyuQuery.getCardNo());
                    return reportQuery(reqData);
                }
        );
        CompletableFuture<JSONObject> sf = CompletableFuture.supplyAsync(() -> {
                    JSONObject reqData = new JSONObject();
                    reqData.put("inter_id", "JF025");
                    reqData.put("name", siyuQuery.getName());
                    reqData.put("cardNo", siyuQuery.getCardNo());
                    reqData.put("mobile", siyuQuery.getTel());
                    return reportQuery(reqData);
                }
        );
        CompletableFuture<JSONObject> xl = CompletableFuture.supplyAsync(() -> {
                    return educationQuery(siyuQuery);
                }
        );
        CompletableFuture<JSONObject> gsgl = CompletableFuture.supplyAsync(() -> {
                    return creditEnterpriseQuery(siyuQuery);
                }
        );
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(smrz, sjsys, blxw, sf, xl, gsgl);
        allFutures.join();

        JSONObject object = new JSONObject();
        try {
            object.put("smrz", smrz.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.put("sjsys", sjsys.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.put("blxw", blxw.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.put("sf", sf.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.put("xl", xl.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.put("gsgl", gsgl.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    @Override
    public JSONObject educationQuery(SiyuQuery siyuQuery) {
        String educationString = redisCache.getCacheObject("EDU::" + siyuQuery.getCardNo());
        if (StringUtils.isNotEmpty(educationString)) {
            return JSON.parseObject(educationString);
        }
        //1.准备客户端
        ApiClient apiClient = new ApiClient("http://101.132.253.231/api", "1000003020240626", "ofSgvvRDQE7b2wwcPBAEFAK5Y8MC2Vg6");
        //2.准备参数
        IdCardVerifyRequst param = new IdCardVerifyRequst();
        param.setFullName(siyuQuery.getName());
        param.setIdCardNo(siyuQuery.getCardNo());
        sysConfigMapper.addInterNum();
        Result<LawSuitResponse> response = apiClient.educationVerifyV4(param);
        if (response.getCode() != 200) {
            JSONObject ret = new JSONObject();
            ret.put("code", response.getCode());
            ret.put("msg", response.getMsg());
            return ret;
        }
        educationString = JSON.toJSONString(response);
        redisCache.setCacheObject("EDU::" + siyuQuery.getCardNo(), educationString, 3, TimeUnit.DAYS);
        return JSON.parseObject(educationString);
    }

    @Override
    public JSONObject creditEnterpriseQuery(SiyuQuery siyuQuery) {
        String creditString = redisCache.getCacheObject("CRE::" + siyuQuery.getCardNo());
        if (StringUtils.isNotEmpty(creditString)) {
            return JSON.parseObject(creditString);
        }
        ApiClient apiClient = new ApiClient("http://101.132.253.231/api", "1000003020240626", "ofSgvvRDQE7b2wwcPBAEFAK5Y8MC2Vg6");
        IdCardVerifyRequst param = new IdCardVerifyRequst();
        param.setIdCardNo(siyuQuery.getCardNo());
        sysConfigMapper.addInterNum();
        Result<LawSuitResponse> response = apiClient.creditEnterpriseV2(param);

        log.debug(response.toString());
        if (response.getCode() != 200) {
            JSONObject ret = new JSONObject();
            ret.put("code", response.getCode());
            ret.put("msg", response.getMsg());
            return ret;
        }
        creditString = JSON.toJSONString(response);
        redisCache.setCacheObject("CRE::" + siyuQuery.getCardNo(), creditString, 3, TimeUnit.DAYS);
        return JSON.parseObject(JSON.toJSONString(response));
    }

    @Override
    public int addImmovablePropertyQuery(SiyuQuery sysQuery) {
        // 1.上传授权文件
        Document document = makeAithFile(sysQuery);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        document.saveToStream(outputStream, FileFormat.PDF);
        document.close();
        String base64EncodedString = Base64.getEncoder().encodeToString(outputStream.toByteArray()).trim();
        ApiClient apiClient = new ApiClient("http://101.132.253.231/api", "1000003020240626", "ofSgvvRDQE7b2wwcPBAEFAK5Y8MC2Vg6");
        UploadAuthFile64Request param = new UploadAuthFile64Request();
        param.setBase64(base64EncodedString);
        param.setFilename("当事人授权书_" + sysQuery.getCardNo() + ".pdf");
        Result<FileInfoResponse> response = apiClient.uploadAuthFile64(param);

//      Result<FileInfoResponse> response = JSON.parseObject("{\"code\":200,\"data\":{\"fileId\":\"6117351581241344\",\"requestId\":" +
//                    "\"6117351817342976\"},\"msg\":\"成功\"}", Result.class);

        log.warn("---上传授权文件返回---：" + JSON.toJSONString(response));
        if (response.getCode() != 200) {
            log.error("调用出错： {}", JSONObject.toJSONString(response));
            new ServiceException("AuthErr");
        }
        // 2.个人不动产信息
        PersonalHouseRequest param_ = new PersonalHouseRequest();
        param_.setFullName(sysQuery.getName());
        param_.setIdCardNo(sysQuery.getCardNo());
        param_.setFileId(response.getData().getFileId());
//          param_.setFileId("6117351581241344");
        param_.setFileTypes("3");

        sysConfigMapper.addInterNum();
        Result<PersonalHouseResponse> response_ = apiClient.getPersonalHouse(param_);

//            Result<PersonalHouseResponse> response_ = JSON.parseObject("{\"code\":200,\"data\":{\"messge\":\"查询成功有结果\",\"requestId\"" +
//                    ":\"6117352146153472\",\"resultCode\":1,\"taskId\":\"8d45a999190d4f3a8d0721bfca6b6e73\"},\"msg\":\"成功\"}", Result.class);

        log.warn("---建立查询任务返回---：" + JSON.toJSONString(response_));
        SiyuImmovable immovable = new SiyuImmovable(sysQuery.getQueryId().intValue(), JSON.toJSONString(response), JSON.toJSONString(response_));
        // 3.主要查询信息
        siyuQueryMapper.insertSiyuImmovable(immovable);

        if (response_.getCode() != 200) {
            log.error("调用出错： {}", JSONObject.toJSONString(response_));
        }
        return immovable.getId();
    }

    @Override
    public AjaxResult immovablePropert(SiyuQuery sysQuery) {
        AjaxResult result = new AjaxResult();
        result.put("success", false);
        Map<String, Object> immovableMap = siyuQueryMapper.selectSiyuImmovableByQueryId(sysQuery.getQueryId());
        // 1. 已发起过历史查询且结果为 审核不通过/审核通过
        if (immovableMap != null) {
            result.putAll(immovableMap);
            if (immovableMap.get("personalRentApply") != null) {
                JSONObject detail = JSON.parseObject(immovableMap.get("personalRentApply").toString()).getJSONObject("data").getJSONObject("detail");
                String approvalStatus = detail.getString("approvalStatus");
                if (!"IN_APPROVAL".equals(approvalStatus)) {
                    JSONArray authResults = detail.getJSONArray("authResults");
                    boolean isPass = true;
                    if (authResults != null) {
                        for (int i = 0; i < authResults.size(); i++) {
                            String authState = authResults.getJSONObject(i).getString("authState");
                            if ("10".equals(authState) || "20".equals(authState)) {
                                isPass = false;
                                break;
                            }
                        }
                    }
                    if (isPass) {
                        result.replace("success", true);
                        return result;
                    }
                }
            } else if (immovableMap.get("personalHouse") != null) {

            } else {
                return result;
            }
        } else {
            return result;
        }
        // 2. 发起查询
        JSONObject data = JSON.parseObject(immovableMap.get("personalHouse").toString()).getJSONObject("data");
        log.warn("---请求获取不动产(任务编号)---：" + data.getString("requestId"));
        ApiClient apiClient = new ApiClient("http://101.132.253.231/api", "1000003020240626", "ofSgvvRDQE7b2wwcPBAEFAK5Y8MC2Vg6");
        GetPersonalHouseResponse param = new GetPersonalHouseResponse();
        param.setIdCardNo(sysQuery.getCardNo());
        param.setTaskId(data.getString("taskId"));
        try {
            Result<PersonalRentApplyResponse> response = apiClient.getPersonalHouseResponse(param);
//            Result<PersonalRentApplyResponse> response = JSON.parseObject("{\n" +
//                    "    \"code\": 200,\n" +
//                    "    \"data\": {\n" +
//                    "        \"detail\": {\n" +
//                    "            \"approvalStatus\": \"APPROVED\",\n" +
//                    "            \"authResults\": [\n" +
//                    "                {\n" +
//                    "                    \"isReAuth\": \"0\",\n" +
//                    "                    \"cardNum\": \"513721199508103873\",\n" +
//                    "                    \"authState\": \"30\",\n" +
//                    "                    \"authStateDesc\": \"核查成功\",\n" +
//                    "                    \"resultList\": [\n" +
//                    "                        {\n" +
//                    "                            \"certNo\": \"宁（2020）中卫市不动产权第T0003344号\",\n" +
//                    "                            \"unitNo\": \"640502101037GB00010F00270066\",\n" +
//                    "                            \"ownership\": \"共同共有\",\n" +
//                    "                            \"rightsType\": \"国有建设用地使用权/房屋所有权\",\n" +
//                    "                            \"rightsEndTime\": \"2080-08-10\",\n" +
//                    "                            \"useTo\": \"住宅\",\n" +
//                    "                            \"isSealUp\": \"否\",\n" +
//                    "                            \"houseArea\": \"156.29\",\n" +
//                    "                            \"location\": \"沙坡头区迎宾大道东侧宁钢·恒祥国际27#楼1-501\",\n" +
//                    "                            \"isMortgaged\": \"是\",\n" +
//                    "                            \"rightsStartTime\": \"2010-08-10\"\n" +
//                    "                        },\n" +
//                    "                        {\n" +
//                    "                            \"certNo\": \"宁（2018）中卫市不动产权第1402814号\",\n" +
//                    "                            \"unitNo\": \"640502104204JC10009F99990001\",\n" +
//                    "                            \"ownership\": \"共同共有\",\n" +
//                    "                            \"rightsType\": \"宅基地使用权/房屋所有权\",\n" +
//                    "                            \"rightsEndTime\": \"1990-01-01\",\n" +
//                    "                            \"useTo\": \"None\",\n" +
//                    "                            \"isSealUp\": \"否\",\n" +
//                    "                            \"houseArea\": \"80.60\",\n" +
//                    "                            \"location\": \"中卫市沙坡头区镇罗镇镇北村10队\",\n" +
//                    "                            \"isMortgaged\": \"是\",\n" +
//                    "                            \"rightsStartTime\": \"1990-01-01\"\n" +
//                    "                        }\n" +
//                    "                    ]\n" +
//                    "                }\n" +
//                    "            ]\n" +
//                    "        },\n" +
//                    "        \"messge\": \"查询成功\",\n" +
//                    "        \"requestId\": \"6117641243683840\",\n" +
//                    "        \"resultCode\": 1\n" +
//                    "    },\n" +
//                    "    \"msg\": \"成功\"\n" +
//                    "}", Result.class);
            String personalRentApply = JSON.toJSONString(response);
            log.warn("---请求获取不动产返回---：" + personalRentApply);
            Date updateTime = DateUtils.getNowDate();
            siyuQueryMapper.updateSiyuImmovablePersonalRentApply((int) immovableMap.get("id"), personalRentApply, updateTime);
            if (response.getCode() == 200) {
                // 即时查询处于审核中
                if ("APPROVED".equals(response.getData().getDetail().getString("approvalStatus"))) {
                    com.alibaba.fastjson.JSONArray authResults = response.getData().getDetail().getJSONArray("authResults");
                    boolean isPass = true;
                    for (int i = 0; i < authResults.size(); i++) {
                        String authState = authResults.getJSONObject(i).getString("authState");
                        if ("10".equals(authState) || "20".equals(authState)) {
                            isPass = false;
                            break;
                        }
                    }
                    if (!isPass) {
                        LocalDateTime createTime = (LocalDateTime) immovableMap.get("createTime");
                        DayOfWeek dayOfWeek = createTime.getDayOfWeek();
                        long daysBetween = ChronoUnit.DAYS.between(createTime, LocalDateTime.now());
                        if (("SATURDAY".equals(dayOfWeek) || "SUNDAY".equals(dayOfWeek)) && daysBetween < 3) {
                            // T+3
                            result.put("time", createTime.plusDays(3));
                            return result;
                        } else if (createTime.getHour() < 17) {
                            // T+1
                            if (daysBetween < 1) {
                                result.put("time", createTime.plusDays(1));
                                return result;
                            }
                        } else {
                            // T+2
                            if (daysBetween < 2) {
                                result.put("time", createTime.plusDays(2));
                                return result;
                            }
                        }
                    }
                } else {
                    result.put("personalRentApply", personalRentApply);
                    result.put("updateTime", updateTime);
                    return result;
                }
                result.put("success", true);
                result.put("personalRentApply", personalRentApply);
                result.put("updateTime", updateTime);
                return result;
            } else {
                return result;
            }
        } catch (Exception e) {
            log.error("调用出错: {}", e);
            return result;
        }
    }

    public void baseFee(SiyuQuery siyuQuery, Long userId) {
        Integer chargeId = siyuChargeMapper.selectSiyuCharge(
                siyuQuery.getQueryId(),
                siyuQuery.getProductId()
        );
        if (chargeId == null) {
            fee(siyuQuery, userId);
        }
    }

    public AjaxResult fee(SiyuQuery siyuQuery, Long userId) {
        Integer productId = siyuQuery.getProductId();
        BigDecimal balance = sysUserMapper.selectUserById(userId).getBalance();
        BigDecimal price;
        SiyuUserPrice siyuUserPrice = siyuUserPriceMapper.selectPriceByUIAadPI(userId, productId);
        if (siyuUserPrice != null) {
            price = siyuUserPrice.getPrice();
        } else {
            price = siyuProductMapper.selectSiyuProductById(productId).getUnitPrice();
        }
        if (price.floatValue() > balance.floatValue()) {
            return AjaxResult.warn("余额不足");
        }
        // 写入扣费记录
        siyuChargeMapper.insertSiyuCharge(new SiyuCharge(
                userId.intValue(),
                "fengkong",
                siyuQuery.getQueryId(),
                balance,
                price,
                balance.subtract(price),
                productId,
                siyuQuery.getAuthCode()
        ));
        return sysUserMapper.subtractBalance(userId.longValue(), price) == 1 ? AjaxResult.success() : AjaxResult.warn("异常");
    }

    public FeeResult reportFee(Integer beiDiaoId, Integer productId, Long userId) {
        BigDecimal balance = sysUserMapper.selectUserById(userId).getBalance();
        BigDecimal price;
        SiyuUserPrice siyuUserPrice = siyuUserPriceMapper.selectPriceByUIAadPI(userId, productId);
        if (siyuUserPrice != null) {
            price = siyuUserPrice.getPrice();
        } else {
            price = siyuProductMapper.selectSiyuProductById(productId).getUnitPrice();
        }
        if (price.floatValue() > balance.floatValue()) {
            return new FeeResult("余额不足");
        }
        // 写入扣费记录
        SiyuCharge siyuCharge = new SiyuCharge(
                userId.intValue(),
                "beidiao",
                beiDiaoId,
                balance,
                price,
                balance.subtract(price),
                productId,
                ""
        );
        siyuCharge.setCreateTime(getNowDate());
        siyuChargeMapper.insertSiyuCharge(siyuCharge);
        sysUserMapper.subtractBalance(userId.longValue(), price);
        return new FeeResult(siyuCharge);
    }

    /**
     * 查询进件记录
     *
     * @param queryId 进件记录主键
     * @return 进件记录
     */
    @Override
    public SiyuQuery selectSiyuQueryByQueryId(Integer queryId) {
        return siyuQueryMapper.selectSiyuQueryByQueryId(queryId);
    }

    /**
     * 新增进件记录
     *
     * @param siyuQuery 进件记录
     * @return 结果
     */
    @Override
    public int insertSiyuQuery(SiyuQuery siyuQuery) {
        return siyuQueryMapper.insertSiyuQuery(siyuQuery);
    }

    /**
     * 修改进件记录
     *
     * @param siyuQuery 进件记录
     * @return 结果
     */
    @Override
    public int updateSiyuQuery(SiyuQuery siyuQuery) {
        return siyuQueryMapper.updateSiyuQuery(siyuQuery);
    }

    /**
     * 批量删除进件记录
     *
     * @param queryIds 需要删除的进件记录主键
     * @return 结果
     */
    @Override
    public int deleteSiyuQueryByQueryIds(Integer[] queryIds) {
        return siyuQueryMapper.deleteSiyuQueryByQueryIds(queryIds);
    }

}
